package cn.uniqueinfo.dp.controller;

import cn.uniqueinfo.dp.exception.UQException;
import cn.uniqueinfo.dp.util.ResultUtil;
import cn.uniqueinfo.dp.vo.Result;
import cn.uniqueinfo.dp.vo.UserVO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author:朱元勋
 * @mail:395910063@qq.com
 * @date:2019-01-05 11:46:08
 * @description:账号登录
 */
@Slf4j
@Api(tags = "账号验证页面")
@Controller
public class LoginController {

    @GetMapping(value = {"/", "/index", "/login"})
    public ModelAndView index() {
        return new ModelAndView("/login/index");
    }

    @GetMapping(value = "/logout")
    @ResponseBody
    public Result logout() {
        return ResultUtil.success("退出成功");
    }

    @PostMapping(value = "/login")
    @ResponseBody
    public Result login(String loginName, String loginPwd) {

        log.info("用户登录验证loginName=[" + loginName + "],loginPwd=[" + loginPwd + "]");
        if (loginName == null
                || loginPwd == null
                || loginName.trim().length() == 0
                || loginPwd.trim().length() == 0) {
            return ResultUtil.fail("登录失败,参数错误");
        }

        // 添加用户验证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(loginName, loginPwd);
        try {
            subject.login(token);
            return ResultUtil.success("登录成功");
        } catch (Exception e) {
            token.clear();
            throw new UQException(0, "user login", "登录失败", e);
        }
    }

    @GetMapping(value = "/error")
    @ResponseBody
    public Result error() {
        return ResultUtil.fail("error");
    }
}
